package com.itheima.web.filter;

import com.itheima.domain.system.User;
import com.itheima.service.system.UserService;
import com.itheima.service.system.impl.UserServiceImpl;
import com.itheima.utils.CookieUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebFilter("/*")
public class AutoLoginFilter implements Filter {
    @Override
    public void destroy() {
    }

    /**
     * @Description: 登录过滤拦截
     * @Param: [req, resp, chain]
     * @return: void
     * @Author: Mr.yuan
     * @Date: 2020/11/30
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        // 优化: 存在cookie,但是用户已经登录了,则不需要进行自动登录
        HttpSession session = request.getSession();
        Object obj = session.getAttribute("user");
        if (obj != null) {
            //用户已经登录
            chain.doFilter(req, resp); // 放行
            return;
        }

        //1. 获取autoLoginCookie的值
        String cookieValue = CookieUtils.getCookieValue(request, "autoLoginCookie");
        //2. 判断是否为空
        if (cookieValue == null) {
            // 没有勾选自动登录
            chain.doFilter(req, resp); // 放行
            return;
        }


        String username = cookieValue.split("&")[0];
        String password = cookieValue.split("&")[1];

        //3. 封装到对象中
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        //4. 调用service登录了
        UserService service = new UserServiceImpl();
        // uu: 查询数据库返回的真实对象.  user: 仅仅封装了用户名和密码而已
        User uu = service.login(user);

        //5. 判断用户是否存在
        if (uu == null) {
            // 登录失败
            request.setAttribute("msg", "用户名或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request, resp);
            return;
        }


        //6. 用户登录成功了
        session.setAttribute("user", uu);
        UserService userService = new UserServiceImpl();
        List<String> permissions = userService.findAllPermissionUrlByUserId(uu.getId());
        session.setAttribute("permissions", permissions);
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
